package zy.service.base.brand.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.base.brand.BrandDAO;
import zy.dao.sys.importinfo.ImportInfoDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.base.brand.T_Base_Brand;
import zy.entity.sys.improtinfo.T_Import_Info;
import zy.service.base.brand.BrandService;
import zy.util.CommonUtil;
import zy.util.ExcelImportUtil;
import zy.util.StringUtil;

@Service
public class BrandServiceImpl implements BrandService{
	
	@Resource
	private BrandDAO brandDAO;
	
	@Resource
	private ImportInfoDAO importInfoDAO;

	@Override
	public PageData<T_Base_Brand> page(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = brandDAO.count(param);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		
		List<T_Base_Brand> list = brandDAO.list(param);
		PageData<T_Base_Brand> pageData = new PageData<T_Base_Brand>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}

	@Override
	public Integer queryByName(T_Base_Brand brand) {
		return brandDAO.queryByName(brand);
	}

	@Override
	public T_Base_Brand queryByID(Integer bd_id) {
		return brandDAO.queryByID(bd_id);
	}

	@Override
	public void save(T_Base_Brand brand) {
		brandDAO.save(brand);
	}

	@Override
	public void update(T_Base_Brand brand) {
		brandDAO.update(brand);
	}

	@Override
	public void del(Integer bd_id) {
		brandDAO.del(bd_id);
	}

	@Override
	public Map<String, Object> parseSavingBrandExcel(Workbook soureWorkBook,
			WritableWorkbook errsheet, int companyid) throws Exception {
		WritableSheet errorSheet = errsheet.getSheet(0);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<T_Base_Brand> brandList = new ArrayList<T_Base_Brand>();
		try {
			Sheet sheet = soureWorkBook.getSheet(0);
			int rsColumns = 1;//
			int rsRows = sheet.getRows(); // 行数
			System.out.println("共计: " + (ExcelImportUtil.getRightRows(sheet)-1) + "条");
			
			int j = 1;// 第二行开始写入错误信息, 错误条数
			int successRow = 0;// 导入成功条数
			String initial = "";
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("companyid", companyid);
			List<String> brands = brandDAO.brandList(param);
			
			for (int i = 1; i < rsRows; i++) { // 如第一行为属性项则从第二行开始取数据
				if (ExcelImportUtil.isBlankRow(sheet, i, rsColumns-1)) { // 空行则跳过
					continue;
				}
				//品牌名称
				Cell cell0 = sheet.getCell(0, i);
				String bd_name = cell0.getContents().trim();
				if (StringUtils.isBlank(bd_name)) {
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, j, rsColumns, "第 _" + (i+1) + "_条,品牌名称不能为空!");
					j++;
					continue;
				}
				boolean tag = false;
				for(int k=0;k<brands.size();k++){
					if(bd_name.equals(brands.get(k))){
						tag = true;
						break;
					}
				}
				if(tag){
					ExcelImportUtil.copySheetRow(errorSheet, sheet, i, j, rsColumns, "第 _" + (i+1) + "_条,品牌名称已存在!");
					j++;
					continue;
				}
				
				// 数据表对象
				T_Base_Brand t_Base_Brand = new T_Base_Brand();
				t_Base_Brand.setBd_name(bd_name);
				t_Base_Brand.setBd_spell(StringUtil.Hanzi2SimpleSpelling(bd_name));
				t_Base_Brand.setBd_state("0");
				t_Base_Brand.setCompanyid(companyid);
				brandList.add(t_Base_Brand);
				
				brands.add(bd_name);//把当前品牌名称放入集合
				successRow++;
			}
			resultMap.put("brandList", brandList);
			resultMap.put("fail", j-1);// 错误条数
			resultMap.put("success", successRow);// 成功条数
		}catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	@Transactional
	@Override
	public void save(Map<String, Object> param) {
		List<T_Base_Brand> brandList = (List<T_Base_Brand>)param.get("brandList");
		T_Import_Info t_Import_Info = (T_Import_Info)param.get("t_Import_Info");
		if(brandList != null && brandList.size()>0){
			brandDAO.save(brandList);
		}
		// 查询当前用户是否导入过数据
		T_Import_Info info = importInfoDAO.queryImportInfo(param);
		if(info != null){
			String temp_uploaddir = CommonUtil.CHECK_BASE + CommonUtil.EXCEL_PATH;
			String last_error_filename = temp_uploaddir + File.separator + info.getIi_error_filename();
			File last_error_file = new File(last_error_filename);
			if (last_error_file.exists()) {
				last_error_file.delete();
			}
			ExcelImportUtil.deleteFile(last_error_file);
			importInfoDAO.updateImportInfo(t_Import_Info);
		}else {
			importInfoDAO.saveImportInfo(t_Import_Info);
		}
	}

}
